import React, {PureComponent} from "react";
import {Link} from 'react-router-dom'
import '../style.css'
import {ListView, Pagination} from "antd-mobile";
import PropTypes from 'prop-types'
import {actions} from "../store";
import {connect} from "react-redux";
import moment from "moment";

class ListViewComponent extends PureComponent {

    static propTypes = {
        name: PropTypes.string
    };

    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });

        this.state = {
            dataSource,
            articleListPage: {},
            articleList: [],
            pageNo: 1,
            // isLoading: true,
        };
    }

    componentDidMount() {
        const {name} = this.props;
        let page = localStorage.getItem(name);
        if (page !== null) {
            this.setState({pageNo: parseInt(page)}, () => {
                this.loadData();
            })
        } else {
            this.loadData();
        }
    }

    loadData = () => {
        const {name} = this.props;
        if (name === '全部') {
            let body = {
                "pageNo": this.state.pageNo,
                "pageSize": 10
            };
            this.props.getArticleList(body, (data) => {
                localStorage.setItem(name, this.state.pageNo.toString());
                this.setState({
                    articleListPage: data,
                    articleList: data.list,
                    dataSource: this.state.dataSource.cloneWithRows(data.list),
                    // isLoading: false,
                });
            });
        } else {
            let body = {
                "pageNo": this.state.pageNo,
                "pageSize": 10,
                "typeName": name
            };
            this.props.getArticleListType(body, (data) => {
                localStorage.setItem(name, this.state.pageNo.toString());
                this.setState({
                    articleListPage: data,
                    articleList: data.list,
                    dataSource: this.state.dataSource.cloneWithRows(data.list),
                    // isLoading: false,
                });
            });
        }
    };

    handleImageError = (e) => {
        //解决刷新问题
        e.target.style.display = 'block';
        e.target.src = "https://www.gifjia5.com/wp-content/themes/dux/img/thumbnail.png";
    };

    handleImageLoad = (e) => {
        //解决刷新问题
        e.target.style.display = 'block';
    };

    separator = (sectionID, rowID) => (
        <div
            key={`${sectionID}-${rowID}`}
            style={{
                backgroundColor: '#F5F5F9',
                height: 8,
                borderTop: '1px solid #ECECED',
                borderBottom: '1px solid #ECECED',
            }}
        />
    );

    onNextChange = (value) => {
        this.setState({
            pageNo: value,
        }, () => {
            this.lv.scrollTo(0, 0);
            this.loadData();
        });
    };

    render() {
        const {articleListPage, articleList, pageNo} = this.state;

        let index = articleList.length - 1;
        const row = (rowData, sectionID, rowID) => {
            if (index < 0) {
                index = articleList.length - 1;
            }
            const obj = articleList[index--];
            return (
                <Link to={{
                    pathname: '/details', query: {
                        id: obj.articleId,
                        title: obj.articleTitle
                    }
                }}>
                    <div key={rowID} style={{padding: '0 10px'}}>
                        <div style={{display: 'flex', padding: '10px 0', minHeight: '100px'}}>
                            <img className={'article-item-img'}
                                 src={obj.articleImg}
                                 onLoad={(e) => this.handleImageLoad(e)}
                                 onError={(e) => this.handleImageError(e)}
                                 alt=""/>
                            <div style={{lineHeight: 1}}>
                                <div style={{
                                    marginBottom: '8px',
                                    fontWeight: 'bold',
                                    color: '#555',
                                    lineHeight: 1.2
                                }}>{obj.articleTitle}</div>
                                <div style={{
                                    color: '#999',
                                    fontSize: '12px',
                                    lineHeight: 1.2,
                                    maxHeight: '43px',
                                    minHeight: '43px',
                                    overflow: 'hidden',
                                    transform: 'translate(0, -2px)'
                                }}><span
                                    style={{color: '#45B6F7'}}>[{moment(obj.articleSendTime * 1000).format('YYYY-MM-DD')}/图{obj.articleImgCount}]</span>{obj.articleNote}
                                </div>
                            </div>
                        </div>
                    </div>
                </Link>
            );
        };
        return (
            <ListView
                ref={el => this.lv = el}
                dataSource={this.state.dataSource}
                renderHeader={() => <div className={'footer'}></div>}
                renderFooter={() => {
                    let page = Math.ceil(articleListPage.totalCount / articleListPage.pageSize);
                    if (isNaN(page)) {
                        page = 0;
                    }
                    return <Pagination total={page}
                                       className="custom-pagination-with-icon"
                                       current={pageNo}
                                       locale={{
                                           prevText: (
                                               <span className="arrow-align">上一页</span>),
                                           nextText: (
                                               <span className="arrow-align">下一页</span>),
                                       }}
                                       onChange={this.onNextChange}
                    />;
                }}
                renderRow={row}
                renderSeparator={this.separator}
                className="am-list"
                pageSize={5}
                useBodyScroll
                onScroll={() => {
                    // console.log('scroll');
                }}
            />
        );
    }
}

const mapState = (state) => ({
    // articleListPage: state.getIn(['home', 'articleListPage']),
});

const mapDispatch = (dispatch) => ({
    getArticleList(body, func) {
        dispatch(actions.getArticleList(body, func))
    },
    getArticleListType(body, func) {
        dispatch(actions.getArticleListType(body, func))
    }
});

export default connect(mapState, mapDispatch)(ListViewComponent);